package com.jiemengshi.server.qiniu;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by MingQi on 2017/6/6.
 */
public class QiniuSaveAs {
    private String bucketName;

    private static Mac mac;
    String accessKey;
    String secretKey;
    
    public QiniuSaveAs(String bucketName, String accessKey, String secretKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        this.bucketName = bucketName;
        this.accessKey = accessKey;
        this.secretKey = secretKey;

        if(mac == null){
            byte[] sk = secretKey.getBytes("utf-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(sk, "HmacSHA1");
            mac = Mac.getInstance("HmacSHA1");
            mac.init(secretKeySpec);
        }
    }

    public String getRequestUrl(String oldUrl, String newKey) throws UnsupportedEncodingException {
        String newUrl = oldUrl + "|saveas/" + UrlSafeBase64.encodeToString(bucketName + ":" + newKey);
        String encodedSign = UrlSafeBase64.encodeToString(mac.doFinal(newUrl.getBytes()));

        return newUrl + "/sign/" + accessKey + ":" + encodedSign;
    }
}
